<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Device extends Backend
{

    /**
     * Cate模型对象
     * @var \app\admin\model\Device
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Device;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function getfangdong(){
        $list = Db::name('user')->where(['is_landlord'=> 1])->select();
        $result = array("total" => count($list), "rows" => $list);

        return json($result);
    }
    public function geteleprice(){
        $list=config('site.eleprice');
        print_r($list);exit;
        $result = array("total" => count($list), "rows" => $list);

        return json($result);
    }
    public function actionsend(){
        $params = $this->request->post("ids");
        if(!$params)$this->error(__('请选择', ''));
        $arr = explode(',',$params);
        foreach ($arr as $k=>$v){
            $d_data = Db::name('device')->where(['id'=>$v])->find();
            $ele_data = Db::name("electric")->where(['device_id'=>$v])->order("id desc")->find();
            $use_data = Db::name('user')->where(['id'=>$d_data['user_id']])->find();
            if($ele_data){
                $strv = $ele_data['endv'];
            }else{
                $strv = 0;
            }
            if($d_data){
                $data['openid']  = $use_data['openid'];
                $data['first']  = "恭喜";
                $data['course_name']  = "恭喜1";
                $data['teacher_name']  = "http://weixin.qq.com/download";
                $data['pagepath']  = "/pages/home/landlord?strv=".$strv."&price=".$d_data['eleprice']."&device_id=".$v;
                self::sendtemplate($data);
            }
        }
        $re_data['code'] = 1;
        $re_data['msg'] = "推送成功";
        $re_data['data'] = "";
        $re_data['url'] = "";
        return json_encode($re_data);
    }
    /**
     * @param $url_page
     * @param $url_scene
     * @return bool|string
     * 通过post方法发送公众号模板消息
     * {"access_token":"56_9T2rAZt02MKBh64zESeUha6YIlSLwrXZXFeCDpoQcAoe53RZ-t900sR71T4mdC7KoFwrLCEp6WQGzac90B2oHoMXaqGQYeHXfWbX_d50fmCzmgrNUn8xWxn-dC9032XP4tqZmtu9oNkdpS05NVEaAIAIQZ","expires_in":7200}
     */
    public function sendtemplate($data)
    {
        header('content-type:text/html;charset=utf-8');
        $config = get_addon_config('epay');
        $appid = $config['wechat']['app_id'];
        $secret =$config['wechat']['app_secret'];
        //$appid = "wx00e6c59afbd831d6";
        // $secret = "0512f5e03e31043ede5f8da14d0c32cc";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".trim(config('site.wechat_appid'))."&secret=".trim(config('site.wechat_appsecret'));
        $weix = file_get_contents($url);//获得网页输出
        $obj=json_decode($weix,true);//解码
        $access_token= $obj['access_token'];//网页授权接口调用凭证
        // $access_token = "56_pGwWkQg_cOGaMfFi_Lz_MWOBFjYA4I8yPKfXJj1jfv0fZDIJ56-M-Pd0OccNjbHlicXbd8BvxsCphCgiBcV8NJMXQU_fhBvHhq4_ryUNYvrUPC5LvvNsqIbvaV3Kyjua7lSNlXByeziLwWwzNWUdAIAIRP";//网页授权接口调用凭证
        //$access_token = WeChatTrait::getAccessToken($appid, $secret);




        $uri ='https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send';
        $uri = $uri.'?access_token='.$access_token;

        $data=  array(
            'access_token' => $access_token,
            'touser'=>$data['openid'],   //发给谁
            'mp_template_msg' => [
                'appid' => $appid,//公众号appid
                'template_id' => 'ChR2OdvLvZUx_L0OTH4Z4KFs2304JYWeNabtpJbGIrc',
                'url' => 'http://weixin.qq.com/download',
                'miniprogram' => [
                    'appid' => trim(config('site.wechat_appid')),//小程序appid
                    //'page' =>  $data['pagepath'],
                    'pagepath' =>  $data['pagepath'],
                    //'pagepath' => 'pages/index/index',
                ],
                'data' => [
                    'first' => ['value' => $data['first'],'color' => '#173177'],
                    'keyword1' => ['value' => $data['course_name'],'color' => '#173177'],
                    //'keyword2' => ['value' => $data['teacher_name']."?".$data['pagepath'],'color' => '#173177'],
                    //'remark' => ['value' => '愉快','color' => '#173177'],
                ],
            ],
            /*'template_id'=>'ChR2OdvLvZUx_L0OTH4Z4KFs2304JYWeNabtpJbGIrc',   //模板id
            'url'=>'#',     //这个是你发送了模板消息之后，当用户点击时跳转的连接
            'topcolor'=>"#FF0000",   //颜色
            'miniprogram' => '',
            'data'=>array(

                'first'=>array(
                    'value'=>$data['first'],
                    'color'=>'#173177'
                ),
                'keyword1'=>array(
                    'value'=>$data['course_name'],
                    'color'=>'#173177'
                ),
                'keyword2'=>array(
                    'value'=>$data['teacher_name'],
                    'color'=>'#173177'
                ),
            )*/
        );
        $res_data = $this->getJson($uri,$data);
        $res_data = json_decode($res_data, true);
        if ($res_data['errcode'] != 0) {
            return false;
        }
        return true;


    }
    public function getJson($url = '', $param = [] ,$contentType = 'json'){
        $ch = curl_init();
        // 请求地址
        curl_setopt($ch, CURLOPT_URL, $url);
        // 请求参数类型
        $param = $contentType == 'json' ? urldecode(json_encode($param)) : http_build_query($param);
        // 关闭https验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // post提交
        if($param){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        }
        // 返回的数据是否自动显示
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 执行并接收响应结果
        $output = curl_exec($ch);
        //print_r($output);exit;
        //{code: 1, msg: "", data: "", url: "/rfDnxZXcKM.php/electric/del", wait: 3}
        // 关闭curl
        curl_close($ch);

        return $output !== false ? $output : false;

    }
}
